import { showToast } from './../../utils/asyncWx'
Component({
  data: {
    secondList: ['7', '8', '9'],
    thirdList: ['4', '5', '6', '+'],
    forthList: ['1', '2', '3', '-'],
    fifthList: ['.', '0'],

    backup: '', //备注
    result: '0', // 计算结果
    isFinished: false, //是否显示完成/=
    isClickPoint: false, //是否有小数点
    intCurrentLen: 0, // 当前result整数部分的长度
    leftPointLen: 0, // 左边小数部分的长度
    rightPointLen: 0, // 右边小数部分的长度
    isAddPoint: false, //是否添加了小数点及小数
    isResultFinished: false //是否完成了计算
  },
  properties: {
    date: {
      type: String,
      value: ''
    }
  },
  observers: {
    // 监听result，动态显示‘=’/‘完成’
    'result': function (result) {
      let reg = /[+/-]/g
      let isInclude = reg.test(result)
      let isEnd = result.substring(result.length - 1) == "+" || result.substring(result.length - 1) == "-"
      let isFinished = (isInclude && !isEnd) ? true : false
      this.setData({
        isFinished
      })
    }
  },
  methods: {
    // 获取时间
    handleClickDate (e) {
      this.setData({
        date: e.detail.value
      })
    },
    // 处理输入备注
    handleInput (e) {
      this.setData({
        backup: e.detail.value
      })
    },
    // 点击0123456.+-时触发
    handleClickItem (e) {
      let { result, isClickPoint } = this.data
      let id = e.target.id
      if (id == '.') { // 点击了点
        this.clickPoint(id, result)
      } else if (id == '+' || id == '-') { // 点击了加/减
        this.clickCalculate(result, id)
      } else { // 数字
        this.clickNum(result, id, isClickPoint)
      }

    },
    // 处理删除
    handleDel () {
      let { result } = this.data
      // 若删除了'.', 则更新结果
      if (!result.includes('.')) {
        this.setData({
          isClickPoint: false,
          isAddPoint: false
        })
      }
      // 如果为0， 不做任何处理
      if (result == '0') return '0'
      // 获取长度
      let len = result.split('').length
      let newResult = result.substring(0, len - 1)
      // 当将字符删除至空时， 自动填补结果为'0'
      if (newResult == '') {
        this.setData({
          result: '0'
        })
        return '0'
      }
      // 更新最新结果
      this.setData({
        result: newResult
      })


    },
    // 处理完成/等于
    handleClickFinish () {
      let { result, isFinished } = this.data
      // 表达式未完成时，不允许触发该操作
      if (!isFinished) return false
      // 获取'+/-'左右的数值
      let resultArr = result.includes('+') ? result.split('+') : result.split('-')
      let type = result.includes('+') ? '+' : '-'
      // 转为浮点类型的数值
      let left = parseFloat(resultArr[0])
      let right = parseFloat(resultArr[1])
      // 由于计算的是支出，不存在负数的情况
      result = type === '+' ? (left + right) : (left - right)
      if (result <= 0) {
        // 更新result
        this.setData({
          result: '0',
          isResultFinished: false
        })
        return showToast('支出不能为0或负数哦~')
      }
      result = Number.isInteger(result) ? `${result}` : `${result.toFixed(2)}`
      // 更新result
      this.setData({
        result,
        isResultFinished: true
      })
    },

    // 点击了数字
    clickNum (result, id, isClickPoint) {
      let { intCurrentLen, leftPointLen, rightPointLen, isAddPoint, isResultFinished } = this.data
      if (isResultFinished) {
        result = '0'
        this.setData({
          result: id,
          isResultFinished: false
        })
      }

      // 1.初始化result
      if (result == '0') {
        result = ''
      }

      // 2.如果点击了小数点，则限制只能再多加两位数字
      if (isClickPoint && result) {
        if (!result.includes('+') && !result.includes('-')) { // +/-只有左边存在数字
          // 左边数字就是result
          leftPointLen = Array.from(result.split('.')[1]).length
          if (leftPointLen < 2) {
            result += id
            this.setData({
              result,
              isClickPoint: true,
              leftPointLen,
              isAddPoint: true,
              isResultFinished: false
            })
          }
        } else {
          // +/-右边存在数字， 提取右边的数字
          let rightNum = result.includes('+') ? result.split('+')[1] : result.split('-')[1]
          if (rightNum && rightNum.includes('.')) {
            rightPointLen = Array.from(rightNum.split('.')[1]).length
            if (rightPointLen < 2) {
              result += id
              this.setData({
                result,
                isClickPoint: true,
                rightPointLen,
                isAddPoint: true,
                isResultFinished: false
              })
            }
          }
        }
      }

      // 3. 提取整数长度
      intCurrentLen = this.getIntLen(this.data.result)
      this.setData({
        intCurrentLen
      })
      // 4.限制整数部分最大长度为8
      if (intCurrentLen < 8 && !isAddPoint) {
        result += id
        this.setData({
          result,
          isResultFinished: false
        })
        // 函数需要在此处调用，否则获取不到完整的result
        intCurrentLen = this.getIntLen(result)
        this.setData({
          intCurrentLen
        })
      }
    },

    // 点击了'+/-'
    clickCalculate (result, type) {
      // 当result最后为小数点时不允许再该点击事件发生
      if (result.substring(result.length - 1) === '.') return false
      // 拼接字符串
      if (result.includes('+') || result.includes('-')) {
        let lastIndex = result.lastIndexOf('+')
        lastIndex = lastIndex === -1 ? result.lastIndexOf('-') : result.lastIndexOf('+')
        type = (type == '+' ? '+' : '-')
        result = result.substring(0, lastIndex) + type
        this.setData({
          result,
          isAddPoint: false
        })
        return false
      }
      result += type
      this.setData({
        result,
        isAddPoint: false,
        isResultFinished: false
      })
    },

    // 点击了'.'号
    clickPoint (id, result) {
      // 限制1：在'+/-'后面不允许加'.'
      if (result.substring(result.length - 1) == '+' || result.substring(result.length - 1) == '-') return false

      // 限制2：左边和右边只能各出现一个小数点
      if (result.includes('+') || result.includes('-')) {
        let numArr = result.includes('+') ? result.split('+') : result.split('-')
        // 提取右边的值
        let numRigth = numArr[1]
        if (numRigth.includes('.')) return false
      } else {
        // 提取左边数值（等于result）
        if (result.includes('.')) return false
      }

      // 拼接字符串
      result += id
      this.setData({
        result,
        isClickPoint: true,
        isAddPoint: true
      })
    },

    // 获取整数部分的长度
    getIntLen (result) {
      // 获取'+/-'右边的整数
      if (result.includes('+') || result.includes('-')) {
        let rightResult = result.includes('+') ? result.split('+')[1] : result.split('-')[1]
        let rightInt = rightResult.includes('.') ? rightResult.split('.')[0] : rightResult
        return rightInt.split('').length
      } else {// 获取'+/-'左边的整数
        let leftInt = result.includes('.') ? result.split('.')[0] : result
        return leftInt.split('').length
      }
    }
  }
})